<template>

  <div class="app-container">
    <div style="margin-bottom: 10px;font-size: 14px;font-weight: normal;font-style: normal; "><span>当前收租金额：{{nowMoney}}&#32;¥</span>&#8195;&#8195;&#8195;<span>归档收租金额：{{archiveMoney}}&#32;¥</span></div>
     <!-- 查询和其他操作 -->
    <div class="filter-container">

      <el-input v-model="listQuery.userId" clearable class="filter-item" style="width: 150px;"
                placeholder="请输收租入ID"/>

      <el-select v-model="listQuery.tenantId" class="filter-item" clearable filterable placeholder="请选择租户姓名">
        <el-option
          v-for="item in tenantIdOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>

      <el-select v-model="listQuery.houseId" clearable style="width: 190px" class="filter-item" filterable
                 placeholder="请选择房屋">
        <el-option
          v-for="item in houseOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>

      <el-select v-model="listQuery.roomId" clearable style="width: 180px" class="filter-item" filterable
                 placeholder="请选择房间">
        <el-option
          v-for="item in roomOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>

      <el-select v-model="listQuery.incomeStatus" clearable style="width: 150px" class="filter-item" filterable
                 placeholder="请选择收租状态">
        <el-option
          v-for="item in incomeStatusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>

      <el-date-picker
        class="filter-item"
        value-format="yyyy-MM-dd"
        v-model="listQuery.payDate"
        type="date"
        placeholder="请选择交租时间">
      </el-date-picker>

      <el-button v-permission="['GET /admin/room/list']" class="filter-item" type="primary" icon="el-icon-search"
                 style="background-color: #8B83D2;border-color: #8B83D2;"
                 @click="handleFilter">查找
      </el-button>
      <el-button v-permission="['POST /admin/room/create']" class="filter-item" type="primary" icon="el-icon-edit"
                 style="background-color: #1AD227;border-color: #1AD227;"
                 @click="handleCreate">添加
      </el-button>

      <el-button v-permission="['POST /admin/room/create']" class="filter-item" type="primary" icon="el-icon-edit"
                 style="background-color: #d28d88;border-color: #d28d88;"
                 @click="handleArchive">归档
      </el-button>
      <!--<el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>-->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。"
              @selection-change="handleSelectionChange" stripe border fit highlight-current-row style="width: 100%"
              row-style="height:35px" cell-style="padding:0">
      <!--<el-table-column align="center" width="120" label="租户姓名" prop="tenantId" sortable/>-->

      <el-table-column type="selection" width="55">
      </el-table-column>

      <el-table-column align="center" width="100" label="租户姓名" prop="tenantId">
        <template slot-scope="scope">
          {{ formatTenantName(scope.row.tenantId) }}
        </template>
      </el-table-column>

      <el-table-column :show-overflow-tooltip="true" align="center" label="租住房间号" prop="roomId">
        <template slot-scope="scope">
          {{ formatRoomName(scope.row.roomId) }}
        </template>
      </el-table-column>

      <el-table-column align="center" width="100" label="收租入" prop="userId"/>

      <el-table-column align="center" width="100" label="收租金额" prop="incomeAmount"/>

      <el-table-column align="center" width="80" label="收租状态" prop="incomeStatus">
        <template slot-scope="scope">
          <!--<el-tag v-if="scope.row.incomeStatus === 0" size="small" type="danger">未收租</el-tag>-->
          <el-tag v-if="scope.row.incomeStatus === 1" size="small" type="success">已收租</el-tag>
          <!--<el-tag v-if="scope.row.incomeStatus === 2" size="small" type="warning">延期</el-tag>-->
          <el-tag v-if="scope.row.incomeStatus === 3" size="small" type="warning">归档</el-tag>
          <!--<el-tag v-if="scope.row.incomeStatus === 4" size="small" type="info">其他</el-tag>-->
        </template>
      </el-table-column>


      <el-table-column align="center" width="80" label="收租方式" prop="incomeType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.incomeType === 0" size="small" type="danger">微信</el-tag>
          <el-tag v-if="scope.row.incomeType === 1" size="small" type="success">支付宝</el-tag>
          <el-tag v-if="scope.row.incomeType === 2" size="small" type="warning">现金</el-tag>
          <el-tag v-if="scope.row.incomeType === 3" size="small" type="info">其他</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="收租时间" prop="incomeTime"/>
      <el-table-column align="center" label="归档时间" prop="archiveTime"/>

      <!--<el-table-column align="center" label="备注" prop="remark"/>-->

      <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/room/update']" type="primary" size="mini"
                     @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-permission="['POST /admin/room/delete']" type="danger" size="mini"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px"
               style="width: 400px; margin-left:50px;">
        <el-form-item label="租户姓名" prop="tenantId">
          <!--<el-input v-model="dataForm.tenantId"/>-->
          <el-select v-model="dataForm.tenantId" filterable placeholder="请选择">
            <el-option
              v-for="item in tenantIdOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="房间号" prop="roomId">
          <el-select v-model="dataForm.roomId" filterable placeholder="请选择">
            <el-option
              v-for="item in roomOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="收租金额" prop="incomeAmount">
          <el-input v-model="dataForm.incomeAmount"/>
        </el-form-item>

        <el-form-item label="收租状态" prop="incomeStatus">
          <el-select v-model="dataForm.incomeStatus" filterable placeholder="请选择">
            <el-option
              v-for="item in incomeStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="收租方式" prop="incomeType">
          <el-select v-model="dataForm.incomeType" filterable placeholder="请选择">
            <el-option
              v-for="item in incomeTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>

<script>
  import {listIncomeRent, createIncomeRent, updateIncomeRent, deleteIncomeRent,archiveIncomeRent,tatolIncomeRent} from '@/api/incomeRent'
  import {tenantIdOptions} from '@/api/tenant'
  import {roomOptions} from '@/api/room'
  import {houseOptions} from '@/api/house'
  import {roleOptions} from '@/api/role'
  import {uploadPath} from '@/api/storage'
  import {getToken} from '@/utils/auth'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

  export default {
    name: 'Admin',
    components: {Pagination},
    data() {
      return {
        uploadPath,
        list: null,
        total: 0,
        nowMoney: 0,
        archiveMoney: 0,
        roleOptions: null,
        roomOptions: null,
        listLoading: true,
        tenantIdOptions: null,
        houseOptions: null,
        multipleSelection: [],
        listQuery: {
          page: 1,
          limit: 20,
          userId: undefined,
          tenantId: undefined,
          roomId: undefined,
          incomeStatus: undefined,
          payDate: undefined
        },
        incomeStatusOptions: [ {
          value: 1,
          label: '已收租'
        },  {
          value: 3,
          label: '归档'
        }],

        incomeTypeOptions: [{
          value: 0,
          label: '微信'
        }, {
          value: 1,
          label: '支付宝'
        }, {
          value: 2,
          label: '现金'
        }, {
          value: 3,
          label: '其他'
        }],

        dataForm: {
          roomId: undefined,
          userId: this.$store.state.user.name,
          tenantId: undefined,
          remark: undefined,
          incomeTime: undefined,
          incomeStatus: undefined,
          incomeAmount: undefined,
          incomeType: undefined
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          username: [
            {required: true, message: '管理员名称不能为空', trigger: 'blur'}
          ],
          password: [{required: true, message: '密码不能为空', trigger: 'blur'}]
        },
        downloadLoading: false
      }
    },
    computed: {
      headers() {
        return {
          'X-Litemall-Admin-Token': getToken()
        }
      }
    },
    created() {
      this.getList()

      tenantIdOptions()
        .then(response => {
          this.tenantIdOptions = response.data.data.list
        })

      houseOptions()
        .then(response => {
          this.houseOptions = response.data.data.list
        })

      roomOptions()
        .then(response => {
          this.roomOptions = response.data.data.list
        })

      tatolIncomeRent()
        .then(response => {
          this.nowMoney = response.data.data.nowMoney
          this.archiveMoney = response.data.data.archiveMoney
        })
    },
    methods: {
      formatTenantName(tenantId) {
        for (let i = 0; i < this.tenantIdOptions.length; i++) {
          if (tenantId === this.tenantIdOptions[i].value) {
            return this.tenantIdOptions[i].label
          }
        }
        return ''
      },

      formatRoomName(roomId) {
        for (let i = 0; i < this.roomOptions.length; i++) {
          if (roomId === this.roomOptions[i].value) {
            return this.roomOptions[i].label
          }
        }
        return ''
      },

      formatLeaseStatus(leaseStatusValue) {
        console.log(leaseStatusValue)
        for (let i = 0; i < this.leaseStatusOptions.length; i++) {
          if (leaseStatusValue === this.leaseStatusOptions[i].value) {
            return this.leaseStatusOptions[i].label
          }
        }
        return ''
      },

      formatRole(roleId) {
        for (let i = 0; i < this.roleOptions.length; i++) {
          if (roleId === this.roleOptions[i].value) {
            return this.roleOptions[i].label
          }
        }
        return ''
      },

      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

      getList() {
        this.listLoading = true
        listIncomeRent(this.listQuery)
          .then(response => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetForm() {
        this.dataForm = {
          roomId: undefined,
          userId: this.$store.state.user.name,
          tenantId: undefined,
          remark: undefined,
          incomeTime: undefined,
          incomeStatus: undefined,
          incomeAmount: undefined,
          incomeType: undefined
        }
      },
      uploadAvatar: function (response) {
        this.dataForm.avatar = response.data.url
      },
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            createIncomeRent(this.dataForm)
              .then(response => {
                this.list.unshift(response.data.data)
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加管理员成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleUpdate(row) {
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            updateIncomeRent(this.dataForm)
              .then(() => {
                for (const v of this.list) {
                  if (v.id === this.dataForm.id) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新房间成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleDelete(row) {
        this.$confirm('是否确认已删除？', '确认信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          row.delFlag = 1
          updateIncomeRent(row)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '删除成功'
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        });
      },
      handleArchive(row) {
        this.$confirm('是否将选择的信息归档？', '确认信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          var ids = this.multipleSelection.map(item => item.id).join()//获取所有选中行的id组成的字符串，以逗号分隔
          let params = new FormData();
          params.append('ids',ids);
          archiveIncomeRent(params)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '归档成功'
              })
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        });
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['房间ID', '房间名称', '房间头像']
          const filterVal = ['id', 'username', 'avatar']
          excel.export_json_to_excel2(
            tHeader,
            this.list,
            filterVal,
            '房间信息'
          )
          this.downloadLoading = false
        })
      }
    }
  }
</script>
